package model.entity.unit;

import model.entity.Entity;
import model.entity.building.Building;
import model.world.World;
import model.world.tile.Tile;
import model.world.tile.TileDirection;

public abstract class Unit extends Entity {
	Tile target;

	protected Unit(World world, Tile parent, int entityID) {
		super(world, parent, entityID);
		if(parent != null)
			currentTile.addPresentUnit(this);
		target = currentTile;
	}

	public boolean workTile(){
		if(currentTile.getOccupyingEntity() == this)
			return true;
		if(currentTile.getOccupyingEntity() != null)
			return false;
		currentTile.addOccupyingEntity(this);
		currentTile.removePresentUnit(this);
		return true;
	}

	public void tick(){
		move();
	}

	private void move() {
		if(target != currentTile){
			long dx = target.getX() - currentTile.getX();
			long dy = target.getY() - currentTile.getY();

			currentTile.removeOccupyingEntity(this);
			currentTile.removePresentUnit(this);
			if(currentTile.getOccupyingEntity() instanceof Building){
				((Building)currentTile.getOccupyingEntity()).removePresentUnit(this);
			}

			Tile next = currentTile.getNeighbor(TileDirection.getDirection(dx, dy));
			next.addPresentUnit(this);
			currentTile = next;
		}
	}

	public boolean atTarget(){
		return target == currentTile;
	}

	public void setTarget(Tile target){
		this.target = target;
	}
}
